package com.seven.ssa.job.cycle;

import cn.hutool.core.collection.CollUtil;
import com.seven.ssa.mapper.QuestionMapper;
import com.seven.ssa.model.dto.question.QuestionEsDTO;
import com.seven.ssa.model.dto.question.QuestionEsDao;
import com.seven.ssa.model.entity.Question;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * P2：增量同步，从题目至ES
 */
@Component
@Slf4j
public class IncSyncQuestionsToEs {
    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private QuestionEsDao questionEsDao;

    /**
     * 每分钟同步过去5分钟内MySQL发生修改的题目
     */
    @Scheduled(fixedRate = 60 * 1000)
    public void run() {
        // 新建题目列表，获取过去5分钟内MySQL发生修改的题目
        long FIVE_MINUTES = 5 * 60 * 1000L;
        Date fiveMinutesAgoDate = new Date(new Date().getTime() - FIVE_MINUTES);
        List<Question> questionListFive = questionMapper.listQuestionWithDelete(fiveMinutesAgoDate);
        if (CollUtil.isEmpty(questionListFive)) {
            log.info("没有发生修改的题目");
            return;
        }
        // 把题目列表转为 ES 实体类
        List<QuestionEsDTO> questionEsDTOListFive = questionListFive.stream()
                .map(QuestionEsDTO::objToDto)
                .collect(Collectors.toList());
        // 分页批量写入到 ES
        final int pageSize = 500;
        int total = questionEsDTOListFive.size();
        log.info("增量写入，从题目至ES，启动！total {}", total);
        for (int i = 0; i < total; i += pageSize) {
            log.info("增量写入 from {} to {}", i, Math.min(i + pageSize, total));
            // 注意同步的数据下标不能超过总数据量
            questionEsDao.saveAll(questionEsDTOListFive.subList(i, Math.min(i + pageSize, total)));
        }
        log.info("增量写入，从题目至ES，结束！ total {}", total);
    }
}
